package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.apis.AccountFeignApi;
import com.atguigu.cloud.apis.StorageFeignApi;
import com.atguigu.cloud.utils.ResultData;
import com.atguigu.cloud.utils.ReturnCodeEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.cloud.entities.Order;
import com.atguigu.cloud.service.OrderService;
import com.atguigu.cloud.mapper.OrderMapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author fafa
* @description 针对表【t_order】的数据库操作Service实现
* @createDate 2024-06-26 17:39:20
*/
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{

    @Resource
    private OrderMapper orderMapper;

    @Resource  //通过feign调用库存微服务
    private StorageFeignApi storageFeignApi;

    @Resource //通过feign调用账户微服务
    private AccountFeignApi accountFeignApi;


    /**
     * 此处使用seata的TA模式
     * TM即调用的方法
     * RM即数据库
     * 此处的方法既是TM也是RM
     * @param order
     */
    @Override
    @GlobalTransactional(name = "zzyy-create-order",rollbackFor = Exception.class) //AT模式
    public void create(Order order) {
        //1.xid全局事务id的检查 [seata]
        String xid = RootContext.getXID();

        //①.新建订单
        log.info("---------开始新建订单: " + "\t" + "xid: " + xid);
        //设置初始订单状态
        order.setStatus(0);
        int insert = orderMapper.insert(order);
        System.out.println(insert);
        if(insert > 0){
            //②.减扣库存
            ResultData decrease = storageFeignApi.decrease(order.getProductId(), order.getCount());
            if(!Objects.equals(decrease.getCode(), ReturnCodeEnum.RC200.getCode())){
                throw new RuntimeException("减少库存失败");
            }
            //③.扣减账户余额
            ResultData decrease1 = accountFeignApi.decrease(order.getUserId(), order.getMoney());
            if(!Objects.equals(decrease1.getCode(), ReturnCodeEnum.RC200.getCode())){
                throw new RuntimeException("减少余额失败");
            }

            //④.修改订单状态，表示已经完成
            order.setStatus(1);
            orderMapper.updateById(order);

        }
        log.info("---------结束新建订单: " + "\t" + "xid: " + xid);

    }
}




